#include "ConcreteAcceptor.h"
#include "IEventHandler.h"

ConcreteAcceptor::ConcreteAcceptor(IReactor<SOCKET> *reactor, INET_Addr& addr, IInfo* _info, QueueManager<QueueElement>* queueManager)
	:IAcceptor(reactor), info(_info)
{
	acceptor.open(addr);
	handle.setConnection(acceptor.getHandle());

	reactor->register_handler(this,ACCEPT_EVENT);

	for(int i = 0; i< NUMBER_OF_SERVICE_HANDLERS; i++)
		serviceHandlers[i] = NULL;

	for(int i=0; i<numWorkers; i++)
	{
		workers[i] = new Worker(queueManager, i);
		workers[i]->start();
	}
}


ConcreteAcceptor::~ConcreteAcceptor(void)
{
	for(int i = 0; i< NUMBER_OF_SERVICE_HANDLERS; i++)
	{
		if(serviceHandlers[i] != NULL)
			delete serviceHandlers[i];
	}

	for(int i=0; i<numWorkers; i++)
	{
		delete workers[i];
	}
}

ServiceHandler<SOCKET>* ConcreteAcceptor::makeServiceHandler()
{
	for(int i = 0; i< NUMBER_OF_SERVICE_HANDLERS; i++)
	{
		if(serviceHandlers[i] == NULL)
		{
			serviceHandlers[i] = new PatientValueEventServer(reactor,info);
			return serviceHandlers[i];
		}
	}
}

void ConcreteAcceptor::acceptServiceHandler(ServiceHandler<SOCKET>* service)
{
	acceptor.accept(stream);
	service->open(&stream);
}

